package com.fatan.xiaopacai.mvvm.viewmodel

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.fatan.xiaopacai.base.BaseViewModel
import com.fatan.xiaopacai.mvvm.model.PuKe
import com.fatan.xiaopacai.mvvm.model.allPuKe
import com.fatan.xiaopacai.util.ToastUtil

/**
 * @author: WangYeTong
 * @date: 2023/12/29 14:45
 * @remake:
 */
class MeiNvChanShenViewModel : BaseViewModel() {
    private val _puKeList1 = mutableStateOf<List<PuKe>>(listOf())
    val puKeList1: MutableState<List<PuKe>>
        get() = _puKeList1
    private val _puKeList2 = mutableStateOf<List<PuKe>>(listOf())
    val puKeList2: MutableState<List<PuKe>>
        get() = _puKeList2
    private val _puKeList3 = mutableStateOf<List<PuKe>>(listOf())
    val puKeList3: MutableState<List<PuKe>>
        get() = _puKeList3

    /**
     * 牌已发完的dialog
     */
    private val _showPukeFinishedDialog = mutableStateOf(false)
    val showPukeFinishedDialog: MutableState<Boolean>
        get() = _showPukeFinishedDialog

    /**
     * 已经抽取的牌
     */
    private val _chanList = mutableStateOf<List<PuKe>>(listOf())

    fun addPuKeList1() {
        addNewPuKe(_puKeList1)
    }

    fun addPuKeList2() {
        addNewPuKe(_puKeList2)
    }

    fun addPuKeList3() {
        addNewPuKe(_puKeList3)
    }

    fun reset() {
        _chanList.value = listOf()
        _puKeList1.value = listOf()
        _puKeList2.value = listOf()
        _puKeList3.value = listOf()
    }

    /**
     * 抽取新牌
     */
    private fun addNewPuKe(stateList: MutableState<List<PuKe>>) {
        if (_chanList.value.size >= allPuKe.size) {
            //牌已抽完，提示重新来过
            _showPukeFinishedDialog.value = true
            return
        }
        stateList.value = stateList.value.toMutableList().apply {
            add(getRandomNotExit())
        }
        removeIfSizeMore2(stateList)
    }

    private fun removeIfSizeMore2(stateList: MutableState<List<PuKe>>) {
        if (stateList.value.size <= 2) {
            return
        }
        stateList.value = stateList.value.subList(stateList.value.size - 2, stateList.value.size)
    }

    private fun getRandomNotExit(): PuKe {
        val puke = allPuKe.random()
        if (_chanList.value.contains(puke)) {
            return getRandomNotExit()
        }
        _chanList.value = _chanList.value.toMutableList().apply { add(puke) }
        return puke
    }

    fun setShowPukeFinishedDialog(showDialog: Boolean) {
        _showPukeFinishedDialog.value = showDialog
    }
}